import React, { useEffect, useState } from 'react';
import {
  Card,
  Typography,
  Row,
  Col,
  Image,
  Tag,
  Button,
  Space,
  Descriptions,
  Table,
  Statistic,
  Progress,
  Tabs,
  List,
  Avatar,
  Rate,
  message,
  Spin,
  Badge,
  Divider,
  Modal,
} from 'antd';
const { confirm } = Modal;
import {
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  ShoppingCartOutlined,
  DollarOutlined,
  UserOutlined,
  CalendarOutlined,
  TagOutlined,
  StarOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ProductService } from '../../services/productService';
import { Product } from '../../types';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

const ProductDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('basic');

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '商品管理', path: '/products' },
      { title: '商品列表', path: '/products' },
      { title: `商品详情` },
    ]));
  }, [dispatch]);

  // 加载商品详情
  useEffect(() => {
    if (id) {
      loadProductDetail();
    }
  }, [id]);

  const loadProductDetail = async () => {
    if (!id) {
      message.error('商品ID不存在');
      return;
    }

    try {
      setLoading(true);
      console.log('正在加载商品详情，ID:', id);

      // 使用真实API获取商品数据
      const productData = await ProductService.getProduct(id);
      console.log('商品详情加载成功:', productData);

      setProduct(productData);
    } catch (error: any) {
      console.error('加载商品详情失败:', error);

      // 根据错误类型显示不同的错误信息
      if (error.response?.status === 404) {
        message.error('商品不存在或已被删除');
        navigate('/products');
      } else if (error.response?.status === 400) {
        message.error('无效的商品ID');
        navigate('/products');
      } else {
        message.error('加载商品详情失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 删除商品
  const handleDelete = () => {
    if (!id || !product) {
      message.error('商品信息不存在');
      return;
    }

    confirm({
      title: '确认删除商品',
      content: `确定要删除商品"${String(product.name || '未知商品')}"吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          console.log('正在删除商品，ID:', id);
          await ProductService.deleteProduct(id);
          message.success('商品删除成功');
          navigate('/products');
        } catch (error: any) {
          console.error('删除商品失败:', error);

          if (error.response?.status === 404) {
            message.error('商品不存在或已被删除');
          } else if (error.response?.status === 403) {
            message.error('没有权限删除此商品');
          } else {
            message.error('删除失败，请稍后重试');
          }
        }
      },
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    const statusConfig = {
      active: { color: 'green', text: '上架中' },
      inactive: { color: 'red', text: '已下架' },
      out_of_stock: { color: 'orange', text: '缺货' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取库存状态
  const getStockStatus = (stock: number) => {
    if (stock === 0) {
      return { status: 'error' as const, text: '缺货' };
    } else if (stock < 50) {
      return { status: 'warning' as const, text: '库存不足' };
    } else {
      return { status: 'success' as const, text: '库存充足' };
    }
  };

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!product) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text type="secondary">商品不存在</Text>
      </div>
    );
  }

  const stockStatus = getStockStatus(Number(product.stock) || 0);

  return (
    <div style={{ padding: '24px' }}>
      {/* 商品基本信息 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={24}>
          <Col span={8}>
            <div style={{ textAlign: 'center' }}>
              <Image.PreviewGroup>
                {Array.isArray(product.images) && product.images.map((image, index) => (
                  <Image
                    key={index}
                    src={image}
                    alt={product.name}
                    width={index === 0 ? 300 : 80}
                    height={index === 0 ? 300 : 80}
                    style={{
                      marginRight: index === 0 ? 0 : 8,
                      marginTop: index === 0 ? 0 : 8,
                      borderRadius: 8
                    }}
                  />
                ))}
                {(!product.images || product.images.length === 0) && (
                  <div style={{ width: 300, height: 300, backgroundColor: '#f5f5f5', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 8 }}>
                    <Text type="secondary">暂无图片</Text>
                  </div>
                )}
              </Image.PreviewGroup>
            </div>
          </Col>
          <Col span={16}>
            <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
              <div style={{ flex: 1 }}>
                <Title level={2} style={{ marginBottom: '16px' }}>
                  {String(product.name || '未知商品')}
                  {product.isFeatured && (
                    <Tag color="gold" style={{ marginLeft: '8px' }}>
                      <StarOutlined /> 推荐
                    </Tag>
                  )}
                  {getStatusTag(product.status || 'active')}
                </Title>

                <div style={{ marginBottom: '16px' }}>
                  <Space size="large">
                    <div>
                      <Text type="secondary">价格：</Text>
                      <Text style={{ fontSize: '24px', color: '#f50', fontWeight: 'bold' }}>
                        ¥{(Number(product.price) || 0).toFixed(2)}
                      </Text>
                      {product.originalPrice && Number(product.originalPrice) > Number(product.price) && (
                        <Text delete style={{ marginLeft: '8px', color: '#999' }}>
                          ¥{(Number(product.originalPrice) || 0).toFixed(2)}
                        </Text>
                      )}
                    </div>
                    <div>
                      <Text type="secondary">库存：</Text>
                      <Badge status={stockStatus.status} text={`${Number(product.stock) || 0} 件`} />
                    </div>
                    <div>
                      <Text type="secondary">销量：</Text>
                      <Text strong>{Number(product.salesCount) || 0}</Text>
                    </div>
                  </Space>
                </div>

                <Paragraph ellipsis={{ rows: 3, expandable: true }}>
                  {String(product.description || '暂无描述')}
                </Paragraph>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary">标签：</Text>
                  {Array.isArray(product.tags) && product.tags.map(tag => (
                    <Tag key={tag} color="blue">{String(tag)}</Tag>
                  ))}
                  {(!product.tags || product.tags.length === 0) && (
                    <Text type="secondary">暂无标签</Text>
                  )}
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary">分类：</Text>
                  <Tag>{String(product.category || '未分类')}</Tag>
                  {product.brand && (
                    <>
                      <Text type="secondary" style={{ marginLeft: '16px' }}>品牌：</Text>
                      <Tag>{String(product.brand)}</Tag>
                    </>
                  )}
                </div>

                <div>
                  <Text type="secondary">店铺：</Text>
                  <Space>
                    <Avatar size="small">{String(product.shopName || '未知店铺')[0]}</Avatar>
                    <Text>{String(product.shopName || '未知店铺')}</Text>
                  </Space>
                </div>
              </div>

              <div style={{ marginTop: '24px' }}>
                <Space>
                  <Button
                    type="primary"
                    icon={<EditOutlined />}
                    onClick={() => navigate(`/products/${product.id || product._id}/edit`)}
                  >
                    编辑商品
                  </Button>
                  <Button
                    icon={<EyeOutlined />}
                    onClick={() => window.open(`/products/${product.id || product._id}/preview`, '_blank')}
                  >
                    预览
                  </Button>
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={handleDelete}
                  >
                    删除
                  </Button>
                </Space>
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 详细信息标签页 */}
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="基本信息" key="basic">
            <Descriptions bordered column={2}>
              <Descriptions.Item label="商品ID">{String(product.id || product._id || '-')}</Descriptions.Item>
              <Descriptions.Item label="商品名称">{String(product.name || '-')}</Descriptions.Item>
              <Descriptions.Item label="分类">{String(product.category || '-')}</Descriptions.Item>
              <Descriptions.Item label="品牌">{String(product.brand || '-')}</Descriptions.Item>
              <Descriptions.Item label="价格">¥{(product.price || 0).toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="原价">
                {product.originalPrice ? `¥${product.originalPrice.toFixed(2)}` : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="库存">{product.stock || 0} 件</Descriptions.Item>
              <Descriptions.Item label="销量">{product.salesCount || 0} 件</Descriptions.Item>
              <Descriptions.Item label="状态">{getStatusTag(product.status)}</Descriptions.Item>
              <Descriptions.Item label="推荐商品">
                {product.isFeatured ? <Tag color="gold">是</Tag> : <Tag>否</Tag>}
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {product.createdAt ? new Date(product.createdAt).toLocaleString() : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {product.updatedAt ? new Date(product.updatedAt).toLocaleString() : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="商品描述" span={2}>
                {String(product.description || '-')}
              </Descriptions.Item>
            </Descriptions>
          </TabPane>

          <TabPane tab="规格参数" key="specifications">
            <Table
              dataSource={Object.entries(product.specifications || {}).map(([key, values], index) => ({
                key: index,
                name: key,
                values: Array.isArray(values)
                  ? values.join(', ')
                  : typeof values === 'object'
                    ? JSON.stringify(values)
                    : String(values || '-'),
              }))}
              columns={[
                {
                  title: '参数名称',
                  dataIndex: 'name',
                  key: 'name',
                  width: 200,
                },
                {
                  title: '参数值',
                  dataIndex: 'values',
                  key: 'values',
                },
              ]}
              pagination={false}
              size="middle"
            />
          </TabPane>

          <TabPane tab="商品图片" key="images">
            <Row gutter={16}>
              {Array.isArray(product.images) && product.images.map((image, index) => (
                <Col key={index} span={6} style={{ marginBottom: '16px' }}>
                  <Card
                    hoverable
                    cover={
                      <Image
                        src={image}
                        alt={`商品图片 ${index + 1}`}
                        height={200}
                        style={{ objectFit: 'cover' }}
                      />
                    }
                    size="small"
                  >
                    <Card.Meta title={`图片 ${index + 1}`} />
                  </Card>
                </Col>
              ))}
              {(!product.images || product.images.length === 0) && (
                <Col span={24}>
                  <div style={{ textAlign: 'center', padding: '40px' }}>
                    <Text type="secondary">暂无商品图片</Text>
                  </div>
                </Col>
              )}
            </Row>
          </TabPane>

          <TabPane tab="销售统计" key="statistics">
            <Row gutter={16}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="总销量"
                    value={product.salesCount || 0}
                    prefix={<ShoppingCartOutlined />}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="销售额"
                    value={(product.salesCount || 0) * product.price}
                    precision={2}
                    prefix="¥"
                    valueStyle={{ color: '#52c41a' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="库存周转率"
                    value={product.stock > 0 ? ((product.salesCount || 0) / product.stock * 100) : 0}
                    precision={1}
                    suffix="%"
                    valueStyle={{ color: '#faad14' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="库存状态"
                    value={product.stock}
                    suffix="件"
                    valueStyle={{
                      color: product.stock === 0 ? '#ff4d4f' :
                        product.stock < 50 ? '#faad14' : '#52c41a'
                    }}
                  />
                </Card>
              </Col>
            </Row>

            <Divider />

            <div style={{ marginTop: '24px' }}>
              <Title level={4}>库存预警</Title>
              <Progress
                percent={Math.min((product.stock / 100) * 100, 100)}
                status={product.stock === 0 ? 'exception' : product.stock < 50 ? 'active' : 'success'}
                format={() => `${product.stock} 件`}
              />
              <Text type="secondary" style={{ marginTop: '8px', display: 'block' }}>
                {product.stock === 0 ? '商品已缺货，请及时补货' :
                  product.stock < 50 ? '库存不足，建议补货' : '库存充足'}
              </Text>
            </div>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default ProductDetail;
